package kr.couponplay.android.adapter;

import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.domain.Deal;
import kr.couponplay.android.util.DisplayUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class AdvertiseAdapter extends ArrayAdapter<Deal> {
	private Context mContext;
	private List<Deal> deals;

	public AdvertiseAdapter(Context context, int layoutResource, List<Deal> deals) {
		super(context, layoutResource, deals);
		this.mContext = context;
		this.deals = deals;
	}
	
	public Deal getItem(int position) {
		return deals.get(position);
//		return deals.get(position % deals.size());
	}
	
	public long getItemId(int position) {
		return deals.get(position).getId();
//		return deals.get(position % deals.size()).getId();
	}
	
	public int getItemSize() {
		return deals.size();
//		return deals.size() * 3;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
//		position = position % deals.size();
		ImageView imageView;
		
		if (convertView == null) {
			imageView = new ImageView(mContext);
		} else {
			imageView = (ImageView)convertView;
		}
		
		Deal deal = deals.get(position);

		try {
			URL url = new URL(deal.getThumbnailImageUrl1());
			URLConnection conn = url.openConnection();
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			Bitmap bm = BitmapFactory.decodeStream(bis);
			
			int width = DisplayUtils.widthPixels(mContext);
			int height = (int) width / 2;
			
			Bitmap resize = Bitmap.createScaledBitmap(bm, width, height, true);//사이즈를 설정한 값으로 줄여주고...
			bis.close();
			imageView.setImageBitmap(resize);
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
		}

		imageView.setScaleType(ImageView.ScaleType.MATRIX);
		return imageView;
	}
}	